// 处理jwt解析
const { sendCode, sendData } = require("@/utils/r/result");
const { ErrorCode } = require("@/utils/r/code");
const myJWT = require("@/utils/jwt");

//admin段的jwt中间件
function JWTAuth() {
  return (req, res, next) => {
    //admin端不需要token的接口
    let not_need_token = ["/api/login"];
    if (not_need_token.includes(req.path)) {
      //不需要鉴权，即不用token的接口
      next();
      return;
    }

    //前端大写后端小写
    let token = req.headers["authorization"];
    // 校验token是否存在
    if (!token) {
      sendCode(res, ErrorCode.ERROR_TOKEN_NOT_EXIST);
      return;
    }
    //对token格式进行解析
    let parts = token.split(" ");
    if (!parts.length === 2 && parts[0] !== "Bearer") {
      sendCode(res, ErrorCode.ERROR_TOKEN_TYPE_WRONG);
      return;
    }

    //解析token的数据
    let cliaims = myJWT.parseToken(parts[1]);

    if (!cliaims) {
      sendData(res, ErrorCode.ERROR_TOKEN_WRONG);
      return;
    }

    //判断token是否过期
    if (Date.now() >= cliaims.exp * 1000) {
      sendCode(res, ErrorCode.ERROR_TOKEN_RUNTIME);
      return;
    }

    //将token中的信息挂载到req对象上
    req["user_info_id"] = cliaims.userId;
    req["role"] = cliaims.role;
    req["uuid"] = cliaims.uuid;
    next();
  };
}

module.exports = JWTAuth;
